/**
* COPYRIGHT. whx. ALL RIGHTS RESERVED.
* Project: just-core
* Author: whx <harrywu304@gmail.com>
* Create On: Apr 17, 2012 10:02:43 AM
*/

package org.justframework.core.router;

import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * mixing router, has multi-level, multi-policy features
 */
public class TreeRouter {
	
	/**
	 * logger
	 */
	private static Logger logger = LoggerFactory.getLogger(TreeRouter.class);
	
	/**
	 * nodes list
	 */
	private String nodeList;
	
	/**
	 * route policy for each level
	 */
	private String policyList;
	
	/**
	 * 
	 */
	private String[] policies;
	
	public TreeRouter(String nodeList, String policyList){
		this.nodeList = nodeList;
		this.policyList = policyList;
		//parse policies
		policies = policyList.split(" # ");
	}
	
	/**
	 * locate node by keys
	 * @param keys keys for multi-level nodes
	 * @return node 
	 */
	public String locate(String... keys){
		String nodes = nodeList;
		int level = 1;
		while(nodes.contains("#")){
			Router<String> r = getRouter(nodes,level);
			String key = null;
			if(keys != null && keys.length > 0){
				key = (keys.length >= level) ? keys[level-1]:keys[0];
			}
			nodes = r.locate(key);
			level++;
		}
		
		if(logger.isTraceEnabled()){
			logger.trace("nodeList [{}]",nodeList);
			String keysString = "";
			if(keys != null && keys.length > 0){
				keysString = Arrays.asList(keys).toString();
			}
			logger.trace("key[{}] located node[{}]",keysString,nodes);
		}
		return nodes;
	}
	
	/**
	 * get router by level
	 * @param level
	 * @return
	 */
	private Router getRouter(String nodes, int level){
		String[] nodeArr = nodes.split(" #{"+level+"}+ ");
		String policy = policies[level-1];
		Router<String> r = RouterFactory.getRouter(policy);
		r.setNodes(Arrays.asList(nodeArr));
		return r;
	}
}
